package com.corner.system.service.impl;

import com.corner.common.config.CornerConfig;
import com.corner.common.core.domain.AjaxResult;
import com.corner.common.core.domain.entity.SysUser;
import com.corner.common.core.domain.model.LoginUser;
import com.corner.common.exception.GlobalException;
import com.corner.common.utils.StringUtils;
import com.corner.common.utils.file.FileUploadUtils;
import com.corner.system.domain.FarmerUser;
import com.corner.system.domain.OperationLog;
import com.corner.system.domain.vo.EditUserInfoValuesVo;
import com.corner.system.domain.vo.EditUserInfoVo;
import com.corner.system.domain.vo.Operation;
import com.corner.system.mapper.DataDesignMapper;
import com.corner.system.mapper.FarmerUserMapper;
import com.corner.system.mapper.OperationLogMapper;
import com.corner.system.mapper.OperationMapper;
import com.corner.system.service.FarmerUserService;
import com.corner.system.service.WorkOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 工单业务层处理
 * 
 * @author corner
 */
@Service
public class WorkOrderServiceImpl implements WorkOrderService
{
    private static final Logger log = LoggerFactory.getLogger(WorkOrderServiceImpl.class);


    @Autowired
    private OperationMapper operationMapper;
    @Autowired
    private FarmerUserMapper farmerUserMapper;
    @Autowired
    private DataDesignMapper dataDesignMapper;

    @Override
    public void applyWorkOrder(MultipartFile oldCard1,
                              MultipartFile oldCard2,
                              MultipartFile oldBook,
                              MultipartFile newCard1,
                              MultipartFile newCard2,
                              MultipartFile newBook,
                              Map userInfo)
    {

        try
        {

            // 上传文件路径
            String filePath = CornerConfig.getUploadPath();
            String operationWay = (String) userInfo.get("operationWay");//修改途径：1公众号 2服务热线
            String category = (String) userInfo.get("category");//修改类别：1修改用户名/身份证件 2修改电话号 3修改地址
            String details = (String) userInfo.get("details");//修改类别：1修改用户名/身份证件 2修改电话号 3修改地址
            Long farmerId = (Long) userInfo.get("farmerId");//修改类别：1修改用户名/身份证件 2修改电话号 3修改地址

            Assert.hasText(operationWay,"修改途径为空");
            Assert.hasText(category,"修改类别为空");

            Operation operation = new Operation();
            operation.setCategory(category);//修改类别：1修改用户名 2修改电话号 3修改地址
            operation.setOperationWay(operationWay);
            operation.setOperationStatus("0");//0未审核
            operation.setFarmerId(farmerId);



            //修改用户名/身份证件
            if("1".equals(category)){
                String oldName = (String)userInfo.get("oldName");//原户名
                String oldIDType = (String)userInfo.get("oldIDType");//旧证件类型 1身份证 2户口本
                String oldNumber = (String)userInfo.get("oldNumber");//原证件号
                String newName = (String)userInfo.get("newName");//新户名
                String newIDType = (String)userInfo.get("newIDType");//新证件类型 1身份证 2户口本
                String newNumber = (String)userInfo.get("newNumber");//新证件号
                String oldCard1FileName = null;
                String oldCard2FileName = null;
                String oldBookFileName = null;
                String newCard1FileName = null;
                String newCard2FileName = null;
                String newBookFileName = null;

                //测试
                if("傻逼".equals(newName)){
                    throw new GlobalException("不许含有侮辱词汇");
                }

                operation.setOldCredentialsType(oldIDType);
                operation.setNewCredentialsType(newIDType);
                operation.setOldName(oldName);
                operation.setNewName(newName);
                operation.setOldCardId(oldNumber);
                operation.setNewCardId(newNumber);

                //原证件为身份证
                if("1".equals(oldIDType)){
                    if(oldCard1 == null ){
                        throw new GlobalException("原身份证件正面照片不能为空");
                    }
                    if(oldCard2 == null){
                        throw new GlobalException("原身份证件背面照片不能为空");
                    }

                    oldCard1FileName = FileUploadUtils.upload(filePath, oldCard1);
                    log.info("oldCard1FileName ->{}",oldCard1FileName);
                    oldCard2FileName = FileUploadUtils.upload(filePath, oldCard2);
                    log.info("oldCard2FileName ->{}",oldCard2FileName);
                    operation.setOldCardUrl1(oldCard1FileName);
                    operation.setOldCardUrl2(oldCard2FileName);
                    //原证件为户口本
                }else{
                    if(oldBook == null){
                        throw new GlobalException("原户口照片不能为空");
                    }
                    oldBookFileName = FileUploadUtils.upload(filePath, oldBook);
                    log.info("oldBookFileName ->{}",oldBookFileName);
                    operation.setOldBookUrl(oldBookFileName);
                }
                //新证件为身份证
                if("1".equals(newIDType)){
                    if(newCard1 == null ){
                        throw new GlobalException("新身份证件正面照片不能为空");
                    }
                    if(newCard2 == null){
                        throw new GlobalException("新身份证件背面照片不能为空");
                    }
                    newCard1FileName = FileUploadUtils.upload(filePath, newCard1);
                    log.info("newCard1FileName ->{}",newCard1FileName);
                    newCard2FileName = FileUploadUtils.upload(filePath, newCard2);
                    log.info("newCard2FileName ->{}",newCard2FileName);

                    operation.setNewCardUrl1(newCard1FileName);
                    operation.setNewCardUrl2(newCard2FileName);
                    //新证件为户口本
                }else{
                    if(newBook == null){
                        throw new GlobalException("新户口照片不能为空");
                    }
                    newBookFileName = FileUploadUtils.upload(filePath, newBook);
                    log.info("newBookFileName ->{}",newBookFileName);
                    operation.setNewBookUrl(newBookFileName);
                }

            }else if("2".equals(category)){//修改电话号
                String oldTel = (String) userInfo.get("oldTel");//
                String newTel = (String) userInfo.get("newTel");//
                if(StringUtils.isBlank(oldTel) || StringUtils.isBlank(newTel)){
                    throw new GlobalException("原电话号码或新电话号码不能为空！");
                }
                operation.setOldTelephone(oldTel);
                operation.setNewTelephone(newTel);

            }else if("3".equals(category)){//修改地址
                String oldAddr = (String) userInfo.get("oldAddr");//
                String newAddr = (String) userInfo.get("newAddr");//
                if(StringUtils.isBlank(oldAddr) || StringUtils.isBlank(newAddr)){
                    throw new GlobalException("原地址或新地址不能为空！");
                }
                operation.setOldAddr(oldAddr);
                operation.setNewAddr(newAddr);

            }

            if(StringUtils.isNotBlank(details)){
                operation.setDetails(details);
            }

            operationMapper.insertOperation(operation);
        }catch (Exception e){
            e.printStackTrace();
            throw new GlobalException(e.getMessage());
        }
    }

    /**
     * 查询操作工单
     * @param operation
     * @return
     */
    @Override
    public List<Operation> selectWorkOrder(Operation operation) {
        List<Operation> operations = operationMapper.selectOperation(operation);
        return operations;
    }

    /**
     * 审批工单同时修改用户信息
     * @param operation
     */
    @Transactional
    @Override
    public void approvalWorkOrder(Operation operation) {
        if(StringUtils.isBlank(operation.getOperationStatus())|| "0".equals(operation.getOperationStatus())){
            throw new GlobalException("操作状态未改变");
        }
        if(operation.getFarmerId()==null){
            throw new GlobalException("农户id为空！");
        }
        operation.setOperationTime(new Date());
        operationMapper.updateOperationById(operation);
        FarmerUser farmerUser = new FarmerUser();
        farmerUser.setFarmerId(operation.getFarmerId());
        String category = operation.getCategory();//修改类别：1修改用户名/身份证件  2修改电话号 3修改地址
        if ("1".equals(category)) {
            farmerUser.setFarmerName(operation.getNewName());
            farmerUser.setIdCard(operation.getNewCardId());
        }else if("2".equals(category)){
            farmerUser.setTelephone(operation.getNewTelephone());
        }else if("3".equals(category)){
            farmerUser.setAddress(operation.getNewAddr());
        }
        farmerUserMapper.updateFarmerUser(farmerUser);

    }


    /**
     * 审批工单,不修改用户信息
     * @param operation
     */
    @Transactional
    @Override
    public void approvalWorkOrderNoEdit(Operation operation) {
        if(operation.getId() == null){
            throw new GlobalException("工单id为空！");
        }
        if(StringUtils.isBlank(operation.getOperationStatus())|| "0".equals(operation.getOperationStatus())){
            throw new GlobalException("操作状态未改变");
        }
        operationMapper.updateOperationById(operation);

    }

    @Override
    public void createOrChangeTel(MultipartFile card1, MultipartFile card2, Map userInfo)throws IOException {
        // 上传文件路径
        String filePath = CornerConfig.getUploadPath();
        String operationWay = (String) userInfo.get("operationWay");//修改途径：1公众号 2服务热线
        String category = (String) userInfo.get("category");//修改类别：1修改用户名/身份证件 2修改电话号 3修改地址
        String reasonType = (String) userInfo.get("reasonType");//修改类别：1修改用户名/身份证件 2修改电话号 3修改地址
        String newName = (String) userInfo.get("name");//新电话号
        String newTelePhone = (String) userInfo.get("newTelePhone");//新电话号
        String oldTelePhone = (String) userInfo.get("oldTelePhone");//原电话号
        String newAddr = (String) userInfo.get("newAddr");//原地址
        String cardNumber = (String) userInfo.get("cardNumber");//身份证号
        String details = (String) userInfo.get("details");//备注
        String mapId = (String) userInfo.get("mapId");//地址id
        String openId = (String) userInfo.get("openId");//openid

//        String remarks = (String) userInfo.get("remarks");//

        Assert.hasText(operationWay,"修改途径为空");
        Assert.hasText(newName,"姓名为空");
        Assert.hasText(category,"修改类别为空");
        Assert.hasText(newTelePhone,"新电话号为空");
        Assert.hasText(cardNumber,"身份证号为空");
        Assert.hasText(newAddr,"地址为空");
        Assert.hasText(mapId,"地址id为空");
        Assert.hasText(openId,"openId为空");

        Operation operation = new Operation();
        operation.setCategory(category);//修改类别：1修改用户名 2修改电话号 3修改地址
        operation.setReasonType(reasonType);//问题类型
        operation.setOperationWay(operationWay);//修改途径
        operation.setOperationStatus("0");//0未审核
        operation.setNewTelephone(newTelePhone);
        operation.setNewName(newName);
        operation.setNewCardId(cardNumber);
        operation.setMapId(mapId);
        operation.setOpenId(openId);
        if(StringUtils.isNotBlank(oldTelePhone)){
            operation.setOldTelephone(oldTelePhone);
        }
        operation.setNewAddr(newAddr);//用户所在村屯地址
        if(StringUtils.isNotBlank(details)){
            operation.setDetails(details);
        }

        String card1FilePath = FileUploadUtils.upload(filePath, card1);
        String card2FilePath = FileUploadUtils.upload(filePath, card2);

        operation.setNewCardUrl1(card1FilePath);
        operation.setNewCardUrl2(card2FilePath);

        operationMapper.insertOperation(operation);


    }

    @Override
    public Map getEditChangeTelPage() {
        //问题类型
        List<Map> order_reason_type = dataDesignMapper.selectDatadesign("ORDER_REASON_TYPE");
        //修改类型
        List<Map> edit_type = dataDesignMapper.selectDatadesign("EDIT_TYPE");
        //修改电话选择地址父节点
        List<Map> tel_parent_map_id = dataDesignMapper.selectDatadesign("TEL_PARENT_MAP_ID");
        Map parentid = tel_parent_map_id.get(0);
        String pid = (String)parentid.get("parameterValue");
        List<Map> addrList = farmerUserMapper.selectAddrByParent(pid);
        Map result = new HashMap();
        result.put("order_reason_type",order_reason_type);//问题类型
        result.put("edit_type",edit_type);//修改类型
        result.put("addrList",addrList);
        return result;
    }
}
